import 'package:flutter/material.dart';
import 'listData.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(primarySwatch: Colors.pink),
        home: Scaffold(
          appBar: AppBar(title: Text('GridView')),
          body: HomePage(),
        ));
  }
}

class HomePage extends StatelessWidget {
  List<Widget> _getData() {
    var list = tempData.map((value) {
      return Container(
        width: 100,
        height: 1200,
        // 设置高度无效，用GridView的childAspectRatio更改高度
        child: Column(
          children: <Widget>[
            Image.network(value['imageUrl']),
            SizedBox(
              height: 5,
            ),
            Text(value['title'])
          ],
        ),
        alignment: Alignment.center,
        decoration: BoxDecoration(
            color: Colors.green,
            border: Border.all(color: Colors.red, width: 1)),
      );
    });
    return list.toList();
  }

  Widget _getItemData(context, index) {
    return Container(
      width: 100,
      height: 1200,
      // 设置高度无效，用GridView的childAspectRatio更改高度
      child: Column(
        children: <Widget>[
          Image.network(tempData[index]['imageUrl']),
          SizedBox(
            height: 5,
          ),
          Text(tempData[index]['title'])
        ],
      ),
      alignment: Alignment.center,
      decoration: BoxDecoration(
          color: Colors.green, border: Border.all(color: Colors.red, width: 1)),
    );
  }

  @override
  Widget build(BuildContext context) {
    // 方法1
    /*return GridView.count(
      crossAxisCount: 3, // 多少列
      crossAxisSpacing: 10, // 水平子 Widget 之间的距离
      mainAxisSpacing: 10, // 垂直子 Widget 之间的距离
      childAspectRatio: 1, //这个参数改每个子项的高度(宽度和高度的比例 宽/高)
      padding: EdgeInsets.all(10),
      children: this._getData(),
    );*/
    // 方法2
    return Container(
      padding: EdgeInsets.all(10),
      child: GridView.builder(
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( // 很长的单词不好记
            crossAxisCount: 3, // 多少列
            crossAxisSpacing: 10, // 水平子 Widget 之间的距离
            mainAxisSpacing: 10, // 垂直子 Widget 之间的距离
            childAspectRatio: 1, //这个参数改每个子项的高度(宽度和高度的比例 宽/高)
          ),
          itemCount: tempData.length,
          itemBuilder: this._getItemData)
    );
  }
}
